import Message from 'tdesign-miniprogram/message/index';
import { cloudHanAPI } from '~/api/post';
import { BOOK_CATEGORIES } from '~/config/categories';
const authUtils = require('~/utils/auth.js');

Page({
  data: {
    // Tab 状态
    currentTab: 'latest', // latest, hot, category
    
    // 分类相关
    categories: BOOK_CATEGORIES,
    selectedCategoryIndex: 0,
    
    // 搜索相关
    searchKeyword: '',
    
    // 书摘列表
    posts: [],
    
    // 加载状态
    loading: false,
    refreshing: false,
    
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      hasMore: true
    },
    
    // 评论相关
    showCommentInput: false,
    commentContent: '',
    currentCommentPostId: null
  },

  onLoad() {
    console.log('云汉页面加载');
    // 检查登录状态，如果已登录再加载数据
    this.checkAuthAndLoadData();
  },


  /**
   * 测试API连接
   */
  async testAPIConnection() {
    try {
      console.log('测试API连接...');
      const testResponse = await cloudHanAPI.getLatestPosts({ page: 1, pageSize: 1 });
      console.log('API连接测试成功:', testResponse);
    } catch (error) {
      console.error('API连接测试失败:', error);
    }
  },

  onShow() {
    // 页面显示时检查登录状态并刷新数据
    this.checkAuthAndLoadData();
  },

  /**
   * 检查认证状态并加载数据
   */
  checkAuthAndLoadData() {
    if (authUtils.isLoggedIn()) {
      console.log('用户已登录，加载云汉页面数据');
      // 测试API连接
      this.testAPIConnection();
      // 加载数据
      this.loadPosts();
    } else {
      console.log('用户未登录，跳转到登录页面');
      authUtils.redirectToLogin('/pages/community/index');
    }
  },

  /**
   * Tab 切换
   */
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    console.log('切换到Tab:', tab);
    this.setData({ 
      currentTab: tab,
      posts: [],
      pagination: {
        page: 1,
        pageSize: 10,
        hasMore: true
      }
    });
    this.loadPosts();
  },

  /**
   * 分类选择
   */
  onCategoryChange(e) {
    const index = e.detail.value;
    console.log('选择分类:', this.data.categories[index].label);
    this.setData({ 
      selectedCategoryIndex: index,
      posts: [],
      pagination: {
        page: 1,
        pageSize: 10,
        hasMore: true
      }
    });
    this.loadPosts();
  },

  /**
   * 分类单选切换
   */
  onCategoryToggle(e) {
    const category = e.currentTarget.dataset.category;
    const categories = this.data.categories.map(item => {
      // 单选模式：只有当前点击的分类为选中状态，其他都设为未选中
      return { ...item, selected: item.value === category.value ? !item.selected : false };
    });
    
    console.log('切换分类选择:', category.label, '选中状态:', !category.selected);
    
    this.setData({ 
      categories,
      posts: [],
      pagination: {
        page: 1,
        pageSize: 10,
        hasMore: true
      }
    });
    
    this.loadPosts();
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  /**
   * 搜索确认
   */
  onSearch() {
    console.log('搜索关键词:', this.data.searchKeyword);
    this.setData({
      posts: [],
      pagination: {
        page: 1,
        pageSize: 10,
        hasMore: true
      }
    });
    this.loadPosts();
  },

  /**
   * 搜索框获得焦点
   */
  onSearchFocus() {
    console.log('搜索框获得焦点');
    // 可以在这里添加搜索框焦点状态的样式变化
  },

  /**
   * 搜索框失去焦点
   */
  onSearchBlur() {
    console.log('搜索框失去焦点');
    // 可以在这里添加搜索框失焦状态的样式变化
  },

  /**
   * 加载书摘列表
   */
  async loadPosts(refresh = false) {
    if (this.data.loading) return;

    const { pagination, currentTab, selectedCategoryIndex, searchKeyword, categories } = this.data;
    
    if (refresh) {
      pagination.page = 1;
      pagination.hasMore = true;
    }

    if (!pagination.hasMore) return;

    this.setData({ loading: true });

    try {
      let response;
      const params = {
        page: pagination.page,
        pageSize: pagination.pageSize
      };

      // 获取选中的分类ID列表
      const selectedCategoryIds = currentTab === 'category' 
        ? categories.filter(item => item.selected).map(item => item.value)
        : [];

      console.log('云汉页面加载数据:', { currentTab, searchKeyword, selectedCategoryIds, params });

      // 根据当前Tab调用不同接口
      switch (currentTab) {
        case 'latest':
          if (searchKeyword) {
            console.log('调用搜索接口 - latest模式');
            const latestSearchParams = {
              ...params,
              keyword: searchKeyword
            };
            // 只有当分类Tab激活且有选中分类时才添加categoryId
            if (selectedCategoryIds.length > 0) {
              latestSearchParams.categoryId = selectedCategoryIds.join(',');
            }
            response = await cloudHanAPI.searchCloudHanPosts(latestSearchParams);
          } else {
            console.log('调用getLatestPosts接口');
            const latestParams = { ...params };
            // 只有当分类Tab激活且有选中分类时才添加categoryId
            if (selectedCategoryIds.length > 0) {
              latestParams.categoryId = selectedCategoryIds.join(',');
            }
            response = await cloudHanAPI.getLatestPosts(latestParams);
          }
          break;
          
        case 'hot':
          if (searchKeyword) {
            console.log('调用搜索接口 - hot模式');
            const hotSearchParams = {
              ...params,
              keyword: searchKeyword
            };
            // 只有当分类Tab激活且有选中分类时才添加categoryId
            if (selectedCategoryIds.length > 0) {
              hotSearchParams.categoryId = selectedCategoryIds.join(',');
            }
            response = await cloudHanAPI.searchCloudHanPosts(hotSearchParams);
          } else {
            console.log('调用getHotPosts接口');
            const hotParams = { ...params };
            // 只有当分类Tab激活且有选中分类时才添加categoryId
            if (selectedCategoryIds.length > 0) {
              hotParams.categoryId = selectedCategoryIds.join(',');
            }
            response = await cloudHanAPI.getHotPosts(hotParams);
          }
          break;
          
        case 'category':
          console.log('调用分类接口，选中的分类IDs:', selectedCategoryIds);
          if (searchKeyword) {
            console.log('调用搜索接口 - category模式');
            const categorySearchParams = {
              ...params,
              keyword: searchKeyword
            };
            if (selectedCategoryIds.length > 0) {
              categorySearchParams.categoryId = selectedCategoryIds.join(',');
            }
            response = await cloudHanAPI.searchCloudHanPosts(categorySearchParams);
          } else {
            if (selectedCategoryIds.length > 0) {
              console.log('调用getPostsByCategory接口');
              // 如果有多个分类，使用第一个分类作为主要分类，其他作为过滤条件
              const primaryCategoryId = selectedCategoryIds[0];
              response = await cloudHanAPI.getPostsByCategory(primaryCategoryId, params);
            } else {
              // 没有选中分类时，显示所有内容
              response = await cloudHanAPI.getLatestPosts(params);
            }
          }
          break;
      }

      console.log('API响应:', response);

      if (!response || response.code !== 200) {
        console.error('接口调用失败，响应:', response);
        throw new Error(`接口调用失败: ${response?.message || '未知错误'}`);
      }

      const { data } = response;
      const { list, total, hasMore } = data;

      // 格式化数据
      const formattedPosts = this.formatPosts(list);

      this.setData({
        posts: refresh ? formattedPosts : [...this.data.posts, ...formattedPosts],
        pagination: {
          ...pagination,
          page: pagination.page + 1,
          hasMore: hasMore
        },
        loading: false
      });
    } catch (error) {
      console.error('加载书摘失败:', error);
      this.setData({ loading: false });
      Message.error({
        context: this,
        content: '加载失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 格式化书摘数据
   */
  formatPosts(posts) {
    // 获取配置文件用于图片地址拼接
    const config = require('~/config/index.js').default;
    
    
    const formattedPosts = posts.map(post => ({
      ...post,
      // 确保书籍信息完整
      book: {
        title: post.book?.title || post.bookTitle || '未知书籍',
        author: post.book?.author || post.bookAuthor || '佚名',
        coverUrl: this.processImageUrl(post.book?.coverUrl || post.bookCover || '/static/home/card0.png', config),
        id: post.book?.id || post.bookId,
        category: post.book?.category || post.bookCategory || 1
      },
      // 确保用户信息完整
      user: {
        nickname: post.user?.nickname || post.userName || '匿名用户',
        title: post.user?.title || post.userTitle || '读者',
        avatar: this.processImageUrl(post.user?.avatar || post.userAvatar || '/static/default-avatar.png', config),
        id: post.user?.id || post.userId
      },
      // 内容处理
      content: post.content || post.quote || '',
      userFeel: post.userFeel || post.thoughts || post.feeling || post.comment || post.userComment || '',
      // 生成感想预览
      userFeelPreview: this.generatePreviewContent(post.userFeel || post.thoughts || post.feeling || post.comment || post.userComment || '', 50),
      // 统计数据
      likeCount: post.likeCount || post.likes || 0,
      commentCount: post.commentCount || post.comments || 0,
      favoriteCount: post.favoriteCount || post.collects || 0,
      // 用户交互状态
      isLiked: post.isLiked || false,
      isFavorited: post.isFavorited || false,
      // 生成预览内容
      previewContent: this.generatePreviewContent(post.content || post.quote || '', 100),
      previewThoughts: this.generatePreviewContent(post.userFeel || post.thoughts || post.feeling || post.comment || post.userComment || '', 50),
      // 默认状态
      isExpanded: false,
      isThoughtsExpanded: false,
      // 格式化时间
      createdAt: this.formatTime(post.createdAt)
    }));


    return formattedPosts;
  },

  /**
   * 处理图片URL，拼接完整的地址
   * @param {string} imageUrl - 图片URL
   * @param {Object} config - 配置对象
   * @returns {string} 完整的图片URL
   */
  processImageUrl(imageUrl, config) {
    if (!imageUrl) return '/static/home/card0.png';
    
    // 如果已经是完整URL或者是静态资源，直接返回
    if (imageUrl.startsWith('http') || imageUrl.startsWith('/static/')) {
      return imageUrl;
    }
    
    // 拼接完整的图片URL
    return `${config.baseUrl}${imageUrl}`;
  },

  /**
   * 添加书摘
   */
  onAddPost() {
    wx.navigateTo({
      url: '/pages/release/index'
    });
  },

  /**
   * 用户资料
   */
  onUserProfile() {
    wx.navigateTo({
      url: '/pages/my/index'
    });
  },

  /**
   * 生成预览内容
   */
  generatePreviewContent(content, maxLength) {
    if (!content) return '';
    if (typeof content !== 'string') return '';
    if (content.length <= maxLength) return content;
    return content.substr(0, maxLength) + '...';
  },

  /**
   * 点赞
   */
  async onLike(e) {
    const { postid: postId, isliked: isLiked } = e.currentTarget.dataset;
    
    try {
      // 前端立即反馈
      const posts = this.data.posts.map(post => {
        if (post.id === postId) {
          post.isLiked = !isLiked;
          post.likeCount = isLiked ? Math.max(0, post.likeCount - 1) : (post.likeCount || 0) + 1;
        }
        return post;
      });
      this.setData({ posts });

      // 异步更新数据库
      if (isLiked) {
        await cloudHanAPI.unlikeQuote(postId);
      } else {
        await cloudHanAPI.likeQuote(postId);
      }
    } catch (error) {
      console.error('点赞失败:', error);
      // 回滚UI状态
      const posts = this.data.posts.map(post => {
        if (post.id === postId) {
          post.isLiked = isLiked;
          post.likeCount = isLiked ? (post.likeCount || 0) + 1 : Math.max(0, post.likeCount - 1);
        }
        return post;
      });
      this.setData({ posts });
      
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 收藏
   */
  async onFavorite(e) {
    const { postid: postId, isfavorited: isFavorited } = e.currentTarget.dataset;
    
    try {
      // 前端立即反馈
      const posts = this.data.posts.map(post => {
        if (post.id === postId) {
          post.isFavorited = !isFavorited;
          post.favoriteCount = isFavorited ? Math.max(0, post.favoriteCount - 1) : (post.favoriteCount || 0) + 1;
        }
        return post;
      });
      this.setData({ posts });

      // 异步更新数据库
      if (isFavorited) {
        await cloudHanAPI.uncollectQuote(postId);
      } else {
        await cloudHanAPI.collectQuote(postId);
      }
    } catch (error) {
      console.error('收藏失败:', error);
      // 回滚UI状态
      const posts = this.data.posts.map(post => {
        if (post.id === postId) {
          post.isFavorited = isFavorited;
          post.favoriteCount = isFavorited ? (post.favoriteCount || 0) + 1 : Math.max(0, post.favoriteCount - 1);
        }
        return post;
      });
      this.setData({ posts });
      
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 评论（保持原有功能）
   */
  onComment(e) {
    console.log('onComment 被调用', e);
    
    const { postId } = e.currentTarget.dataset;
    console.log('获取到的 postId:', postId);
    
    if (!postId) {
      console.error('未获取到 postId');
      return;
    }
    
    // 检查登录状态
    if (!authUtils.isLoggedIn()) {
      console.log('用户未登录，跳转到登录页面');
      Message.warning({
        context: this,
        offset: [20, 32],
        content: '请先登录再评论',
        duration: 2000
      });
      authUtils.redirectToLogin();
      return;
    }
    
    console.log('显示评论输入框');
    
    // 先重置状态，然后显示评论输入框（确保重新渲染）
    this.setData({
      showCommentInput: false
    }, () => {
      // 使用 nextTick 确保重置完成后再显示
      wx.nextTick(() => {
        this.setData({
          showCommentInput: true,
          currentCommentPostId: postId,
          commentContent: ''
        });
      });
    });
  },

  /**
   * 查看评论详情页（新增）
   */
  onViewCommentDetail(e) {
    const { postid: postId } = e.currentTarget.dataset;
    console.log('跳转到评论详情页，postId:', postId);
    
    if (!postId) {
      console.error('未获取到 postId');
      return;
    }
    
    // 找到对应的卡片数据
    const post = this.data.posts.find(p => p.id === postId);
    if (!post) {
      console.error('未找到对应的卡片数据');
      return;
    }
    
    // 将完整的卡片数据存储到全局状态
    getApp().globalData.currentPostDetail = post;
    
    // 跳转到独立的详情页
    wx.navigateTo({
      url: `/pages/post-detail/index?id=${postId}&tab=comments`
    });
  },

  /**
   * 分享（转发功能暂时隐藏，后续开发）
   */
  // onShare(e) {
  //   const { post } = e.currentTarget.dataset;
  //   wx.showShareMenu({
  //     withShareTicket: true,
  //     menus: ['shareAppMessage', 'shareTimeline']
  //   });
  // },

  /**
   * 查看全部评论
   */
  onViewAllComments(e) {
    const { postId } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/post-detail/index?id=${postId}&tab=comments`
    });
  },

  /**
   * 隐藏评论输入框
   */
  onHideCommentInput() {
    this.setData({
      showCommentInput: false,
      commentContent: '',
      currentCommentPostId: null
    });
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  /**
   * 发送评论
   */
  async onSendComment() {
    const { commentContent, currentCommentPostId } = this.data;
    
    // 检查评论内容
    if (!commentContent || commentContent.trim() === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        content: '请输入评论内容',
        duration: 2000
      });
      return;
    }

    // 检查登录状态
    if (!authUtils.isLoggedIn()) {
      Message.warning({
        context: this,
        offset: [20, 32],
        content: '请先登录再评论',
        duration: 2000
      });
      authUtils.redirectToLogin();
      return;
    }

    try {
      // 调用评论接口
      await cloudHanAPI.commentQuote(currentCommentPostId, {
        content: commentContent.trim(),
        parentId: null // 暂不支持回复评论
      });

      // 评论成功
      Message.success({
        context: this,
        offset: [20, 32],
        content: '评论成功',
        duration: 2000
      });

      // 更新评论数量
      this.updatePostCommentCount(currentCommentPostId, 1);

      // 隐藏评论输入框
      this.onHideCommentInput();

      // 重新加载当前页面数据以显示新评论
      setTimeout(() => {
        this.loadData();
      }, 500);

    } catch (error) {
      console.error('评论失败:', error);
      Message.error({
        context: this,
        offset: [20, 32],
        content: '评论失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 更新书摘的评论数量
   */
  updatePostCommentCount(postId, increment) {
    const posts = this.data.posts.map(post => {
      if (post.id === postId) {
        return {
          ...post,
          commentCount: (post.commentCount || 0) + increment
        };
      }
      return post;
    });

    this.setData({ posts });
  },

  /**
   * 展开/收起书摘内容
   */
  onExpandContent(e) {
    const { postid: postId } = e.currentTarget.dataset;
    const { posts } = this.data;
    const postIndex = posts.findIndex(post => post.id === postId);
    
    if (postIndex !== -1) {
      posts[postIndex].isExpanded = !posts[postIndex].isExpanded;
      this.setData({ posts: [...posts] });
    }
  },

  /**
   * 展开/收起感想内容
   */
  onExpandThoughts(e) {
    const { postid: postId } = e.currentTarget.dataset;
    const { posts } = this.data;
    const postIndex = posts.findIndex(post => post.id === postId);
    
    if (postIndex !== -1) {
      posts[postIndex].isThoughtsExpanded = !posts[postIndex].isThoughtsExpanded;
      this.setData({ posts: [...posts] });
    }
  },

  // 卡片点击跳转详情页
  onCardTap(e) {
    const post = e.currentTarget.dataset.post;
    wx.navigateTo({
      url: `/pages/post-detail/index?id=${post.id}`
    });
  },

  /**
   * 下拉刷新
   */
  async onRefresh() {
    this.setData({ refreshing: true });
    await this.loadPosts(true);
    this.setData({ refreshing: false });
  },

  /**
   * 上滑加载更多
   */
  onLoadMore() {
    this.loadPosts();
  },

  /**
   * 刷新数据
   */
  refreshData() {
    this.setData({
      posts: [],
      pagination: {
        page: 1,
        pageSize: 10,
        hasMore: true
      }
    });
    this.loadPosts();
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      return date.toLocaleDateString();
    }
  }
});
